const Storage = require('ee-core/storage')
const neuronDb = Storage.connection('neuronDb')


/**
 * 初始化json对象
 * @param dataBaseKey
 */
function initDataBase(dataBaseKey) {
    let dataStr = getDataBaseInfo(dataBaseKey)
    if (!dataStr) {
        setDataBaseInfo(dataBaseKey,new Array())
    }
}

/**
 * 新增记录
 * @param dataBaseKey 数据key
 * @param data 数据
 * @returns {boolean}
 */
exports.insertJsonDbRow=function insertJsonDbRow(dataBaseKey, data) {
    initDataBase(dataBaseKey)
    let localData = getDataBaseInfo(dataBaseKey)
    if(typeof data==='string'){
        data=JSON.parse(data)
    }
    data.mainData.id=getPrimaryKey()
    let count = localData.push(data.mainData)
    setDataBaseInfo(dataBaseKey, localData)
    return count > 0
}
/**
 * 修改记录
 * @param dataBaseKey 数据key
 * @param data 数据
 * @returns {boolean}
 */
exports.updateJsonDbRow=function updateJsonDbRow(dataBaseKey, data) {
    initDataBase(dataBaseKey)
    let localData = getDataBaseInfo(dataBaseKey)
    let localRow
    if (typeof data === 'string') {
        localRow = localData.find(row => row.id === JSON.parse(data).mainData.id)
    } else {
        localRow = localData.find(row => row.id === data.mainData.id)
    }
    if (!localRow) {
        return false
    }
    let index = localData.indexOf(localRow)
    if (index !== -1) {
        localData.splice(index, 1)
    }
    let count
    if (typeof data === 'string') {
        count = localData.push(JSON.parse(data).mainData)
    } else {
        count = localData.push(data.mainData)
    }
    setDataBaseInfo(dataBaseKey, localData)
    return count > 0
}

/**
 * 删除一行数据
 * @param dataBaseKey
 * @param id
 * @returns {boolean}
 */
exports.deleteJsonDbRow=function deleteJsonDbRow(dataBaseKey, id) {
    initDataBase(dataBaseKey)
    let localData = getDataBaseInfo(dataBaseKey)
    let localRow = localData.find(row => row.id === id)
    if (!localRow) {
        return false
    }
    let index = localData.indexOf(localRow)
    if (index !== -1) {
        localData.splice(index, 1)
    }
    setDataBaseInfo(dataBaseKey,localData)
    return true
}

function deleteAll(dataBaseKey){
    initDataBase(dataBaseKey)
    setDataBaseInfo(dataBaseKey,new Array())
}

/**
 * 获取所有数据
 * @param dataBaseKey
 * @returns {any}
 */
function getDataBaseInfo(dataBaseKey) {
    let dbData=neuronDb.getItem(dataBaseKey)
    if(dbData){
        return JSON.parse(dbData)
    }
    return new Array()
}

exports.getDataBaseInfo=function (dataBaseKey) {
  return   getDataBaseInfo(dataBaseKey)
}

/**
 * 保存数据
 * @param dataBaseKey
 * @param data
 */
function setDataBaseInfo(dataBaseKey, data) {
    return neuronDb.setItem(dataBaseKey, JSON.stringify(data))
}


function getPrimaryKey(){
    let timestamp =new Date().getTime()
    let randomNumber=Math.floor(Math.random()*10000);
    let primaryKey=(timestamp+''+randomNumber)*1;
    return primaryKey
}
